package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.UserLoginService;
import com.changgou.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;


/**
 * @author 戴金华
 * @date 2019-12-12 11:05
 */
@Controller
@RequestMapping("/user")
public class UserLoginController {

    //客户端id
    @Value("${auth.clientId}")
    private String clientId;
    //客户端密钥
    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 登录方法
     * 参数传递:
     * 1.账户         username=heima
     * 2.密码         password=123456
     * 3.授权方式      grant_type=password
     * 请求头传递
     *      4Basic base64(客户端id：客户端密钥) Authorization=Basic ....(base64字符串)
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response) throws Exception {
        //授权方式 密码授权方式
        String grant_type = "password";
        AuthToken token = userLoginService.login(username, password, clientId, clientSecret, grant_type);
        //登录成功之后 将token放置到cookie以及redis中
        response.addCookie(new Cookie("Authorization",token.getAccessToken()));
        redisTemplate.boundValueOps("Authorization").set(token.getAccessToken());
        return new Result(true, StatusCode.OK,"登录成功",token);
    }

    @RequestMapping("/toLogin")
    public String toLogin(@RequestParam(required = false,value = "From",defaultValue = "") String from, Model model){
        from.replace("%2F","/");
        model.addAttribute("from",from.toString());
        return "login";
    }
}
